'use strict';

/**
 * @ngdoc function
 * @name sfhtHaitaoCmsApp.controller:PageEditCtrl
 * @description
 * # PageEditCtrl
 * Controller of the sfhtHaitaoCmsApp
 */
angular.module('sfhtHaitaoCmsApp')
    .controller('PageEditCtrl',
        function($scope, $modal, $log, $routeParams, $location, $injector, HTML_MODULE_LIST, RICH_HTML_MODULE_LIST, PageStore, clipboard) {
            //页面使用的模块
            $scope.modules = [];
            //页面配置信息
            $scope.info = null;
            //所有可用的模块
            $scope.moduleLists = null;
            var pageService = $injector.get("PageService");
            var commonBizService = $injector.get("CommonBiz");
            var clipboard = null;

            /**
             * 布局id默认为1
             */
            $scope.init = function() {
                pageService.getPageDetail($routeParams.pageid).then(function(data) {
                    $scope.info = data;
                    if (data.pageConfig && data.pageConfig.pageLayoutConfigs && data.pageConfig.pageLayoutConfigs.length > 0) {
                        $scope.modules = data.pageConfig.pageLayoutConfigs[0].layoutModuleConfigs;
                    }
                }).then(function(data) {
                    pageService.getModuleList($scope.info.pageType).then(function(data) {
                        $scope.allModuleLists = data.value;
                        $scope.groupModuleList = [];
                        $scope.modulesByGroup = {};
                        _.each($scope.allModuleLists, function(value, index, list) {
                            $scope.allModuleLists[index].right = true;

                            if (!$scope.modulesByGroup[value.categoryName]) {
                                $scope.modulesByGroup[value.categoryName] = [];
                                $scope.groupModuleList.push(value.categoryName);
                            }
                            $scope.modulesByGroup[value.categoryName].push(value);
                        });

                        $scope.moduleLists = $scope.modulesByGroup[$scope.groupModuleList[0]];
                    });
                }).then(function(data) {
                    $scope.$watch("modules", function(modules) {
                        if (modules) {
                            for (var indexInLayout = 0; indexInLayout < modules.length; indexInLayout++) {
                                var module = modules[indexInLayout];
                                if (module.right) {
                                    module.right = false;
                                    pageService.getModuleDetail(module.moduleName, $scope.info.pageType, false)
                                        .then(function(data) {
                                            var modal = $modal.open({
                                                animation: true,
                                                templateUrl: 'page.module.eidt.html',
                                                controller: 'ModalCreateModuleCtrl',
                                                resolve: {
                                                    pageid: function() {
                                                        return $routeParams.pageid;
                                                    },
                                                    idInPage: function() {
                                                        return 1;
                                                    },
                                                    indexInLayout: function() {
                                                        return indexInLayout;
                                                    },
                                                    moduleDetail: function() {
                                                        return data;
                                                    }
                                                }
                                            });
                                            modal.result.then(function(returnValue) {
                                                if (!returnValue.cancel) {
                                                    $scope.modules[returnValue.indexInLayout] = returnValue.data;
                                                } else {
                                                    $scope.modules = _.reject($scope.modules, function(value, index, list) {
                                                        return index == returnValue.indexInLayout;
                                                    });
                                                }
                                            }, function() {});
                                        });
                                    break;
                                }
                            };
                        }
                    }, true);
                });
            };

            $scope.displayModuleGroup = function(btnName) {
                $scope.moduleLists = $scope.modulesByGroup[btnName];
            };

            /**
             * 保存页面拖动
             * @return {[type]} [description]
             */
            $scope.save = function() {
                if (window.confirm("确定保存？")) {
                    var config = $scope.info.pageConfig;
                    config.pageLayoutConfigs[0].layoutModuleConfigs = $scope.modules;
                    pageService.recordModuleMove($scope.info.id, config).then(function(data) {}, function(data) {
                        alert("保存失败," + data)
                    });
                }
            };
            /**
             * 发布数据
             */
            $scope.publishData = function() {
                if (window.confirm("确认发布?")) {
                    commonBizService.publishData($scope.info.id, null)
                        .then(function(data) {
                            alert("发布成功!");
                        }, function(data) {
                            alert("发布失败!" + data);
                        });
                }
            };
            /**
             *打开专题页地址
             **/
            $scope.viewOnline = function() {
                commonBizService.getAccessURL($scope.info.id)
                    .then(function(data) {
                            window.open(data.value);
                        });
            };
            /**
             * 删除模块
             * @param  {[type]} module [description]
             * @return {[type]}        [description]
             */
            $scope.remove = function(module) {
                if (window.confirm("确定要删除模块吗？")) {
                    pageService.removeModuleFromPage($scope.info.id, $scope.info.pageConfig.pageLayoutConfigs[0].idInPage, module.idInLayout)
                        .then(function(data) {
                            $scope.modules = _.reject($scope.modules, function(value, i, list) {
                                return value.idInLayout == module.idInLayout;
                            })
                        });
                }
            };

            /**
             * 编辑页面
             * @param  {[type]} module [description]
             * @return {[type]}        [description]
             */
            $scope.edit = function(module) {
                pageService.getModuleDetail(module.moduleName, $scope.info.pageType)
                    .then(function(data) {
                        var modal = $modal.open({
                            animation: true,
                            templateUrl: 'page.module.eidt.html',
                            controller: 'ModalEditModuleCtrl',
                            resolve: {
                                pageid: function() {
                                    return $routeParams.pageid;
                                },
                                idInPage: function() {
                                    return 1;
                                },
                                idInLayout: function() {
                                    return module.idInLayout;
                                },
                                moduleConfig: function() {
                                    return module;
                                },
                                moduleDetail: function() {
                                    return data;
                                }
                            }
                        });
                        modal.result.then(function(returnValue) {
                            _.each($scope.modules, function(value, key, list) {
                                if (value.idInLayout === returnValue.data.idInLayout) {
                                    $scope.modules[key] = returnValue.data;
                                }
                            });
                        });
                    });
            };
            /**
             * 修改页面属性
             * @description 打开modal编辑页面基本信息
             * @param  {[type]}
             * @return {[type]}
             */
            $scope.open = function(pageid) {
                pageService.getResourceConfigs()
                    .then(function(data) {
                        var modal = $modal.open({
                            animation: true,
                            templateUrl: 'page.property.edit.html',
                            controller: 'ModalCreatePageCtrl',
                            resolve: {
                                page: function() {
                                    return $scope.info;
                                },
                                headers: function() {
                                    var headers = [];
                                    _.each(data.value, function(value, key, list) {
                                        headers.push({
                                            name: value.name,
                                            description: value.description,
                                            resourceType :value.resourceType
                                        });
                                    });
                                    return headers;
                                }
                            }
                        });
                        modal.result.then(function(pageId) {
                            //donothing
                        }, function() {
                            $log.info('Modal dismissed at: ' + new Date());
                        });
                    }, function(data) {
                        alert("获取可用头部失败:" + data);
                    });
            };
            $scope.goto = function(fn, moduleName, pageId, placeHolder) {
                if (_.find(HTML_MODULE_LIST, function(name) {
                        return name == moduleName;
                    })) {
                    $location.path('/module/html/' + $scope.info.pageType + "/" + moduleName + '/' + fn + '/' + pageId + '/' + placeHolder);
                } else if (_.find(RICH_HTML_MODULE_LIST, function(name) {
                        return name == moduleName;
                    })) {
                    $location.path('/module/richhtml/' + $scope.info.pageType + "/" + moduleName + '/' + fn + '/' + pageId + '/' + placeHolder);
                } else {
                    $location.path('/module/common/' + $scope.info.pageType + "/" + moduleName + '/' + fn + '/' + pageId + '/' + placeHolder);
                }
            };
        })
    //向页面中增加模块
    .controller('ModalCreateModuleCtrl', function($scope, $modalInstance, $injector, PageService, pageid, idInPage, indexInLayout, moduleDetail, Uploader) {
        var pageService = $injector.get("PageService");
        $scope.showDetail = false;
        $scope.moduleDetail = null;
        $scope.moduleConfig = null;
        $scope.init = function() {
            $scope.moduleDetail = moduleDetail;
            $scope.moduleConfig = {
                moduleName: moduleDetail.moduleName,
                description: moduleDetail.description,
                moduleTitle: '',
                moduleSubTitle: '',
                moduleSubModuleConfigs: [],
                headType: 'LEFT',
                rightLink: '',
                canSlide: false,
                slideTime: 3600,
                style: {
                    marginBottom: -1,
                    border: -1,
                    backgroundColor: '#F5F5F5',
                }
            };
            // 初始化对所有数组进行赋值
            _.each(moduleDetail.cmsSubModuleList, function(value, skey, slist) {
                var defaultProcessor = value.cmsDataProcessor[0];
                $scope.moduleConfig.moduleSubModuleConfigs.push({
                    subModuleId: value.id,
                    processorBeanName: defaultProcessor.beanName,
                    paramInfos: $scope.getParamInfos(defaultProcessor)
                });
            });
        };

        $scope.changeProcssor = function(submoduleConfig, processors) {
            submoduleConfig.paramInfos = $scope.getParamInfos(_.findWhere(processors, {
                'beanName': submoduleConfig.processorBeanName
            }))
        };
        $scope.showDetail = function() {
            $scope.showDetail = !$scope.showDetail;
        };
        $scope.getParamInfos = function(processor) {
            var paramInfos = [];
            if (processor.paramInfos) {
                _.each(processor.paramInfos, function(value) {
                    paramInfos.push({
                        description: value.description,
                        name: value.name
                    });
                });
            };
            return paramInfos;
        };
        $scope.changeFile = function(uploadField) {
            Uploader.uploadFile($scope, null, uploadField);
        };
        $scope.ok = function() {
            _.each($scope.moduleConfig.moduleSubModuleConfigs, function(svalue) {
                var tmp = {};
                _.each(svalue.paramInfos, function(value) {
                    tmp[value.name] = value.value;
                });
                svalue.processorParameters = JSON.stringify(tmp);
            });
            pageService.addModule(pageid, idInPage, indexInLayout, $scope.moduleConfig)
                .then(function(data) {
                    var returnValue = {
                        "cancel": false,
                        "indexInLayout": indexInLayout,
                        "data": data
                    };
                    $modalInstance.close(returnValue);
                }, function(data) {
                    var returnValue = {
                        "cancel": true,
                        "indexInLayout": indexInLayout
                    };
                    $modalInstance.close(returnValue);
                });
        };
        $scope.cancel = function() {
            var returnValue = {
                "cancel": true,
                "indexInLayout": indexInLayout
            };
            $modalInstance.close(returnValue);
        };
    })
    //编辑模块信息
    .controller('ModalEditModuleCtrl', function($scope, $modalInstance, $injector, pageid, idInPage, idInLayout, moduleConfig, moduleDetail, Uploader) {
        var pageService = $injector.get("PageService");
        $scope.showDetail = false;
        $scope.moduleConfig = null;
        $scope.moduleDetail = null;
        $scope.init = function() {
            $scope.moduleConfig = moduleConfig;
            $scope.moduleDetail = moduleDetail;
            _.each($scope.moduleConfig.moduleSubModuleConfigs, function(svalue) {
                //子模块详情
                var submoduleDetail = _.findWhere(moduleDetail.cmsSubModuleList, {
                    "id": svalue.subModuleId
                });
                //子模块使用的处理器
                var selectedProcessor = _.findWhere(submoduleDetail.cmsDataProcessor, {
                    "beanName": svalue.processorBeanName
                });
                //处理器参数
                svalue.paramInfos = $scope.getParamInfos(selectedProcessor, svalue.processorParameters ? JSON.parse(svalue.processorParameters) : null);
            });
        };
        /**
         * 变更处理器
         * @param  {[type]} submoduleConfig [description]
         * @param  {[type]} processors      [description]
         * @return {[type]}                 [description]
         */
        $scope.changeProcssor = function(submoduleConfig, processors) {
            submoduleConfig.paramInfos = $scope.getParamInfos(_.findWhere(processors, {
                'beanName': submoduleConfig.processorBeanName
            }), null);
        };

        /**
         * 处理器参数信息
         * @param  {[type]} processor           [处理器参数信息]
         * @param  {[type]} processorParameters [处理器参数值]
         * @return {[type]}                     [description]
         */
        $scope.getParamInfos = function(processor, processorParameters) {
            var paramInfos = [];
            if (processor.paramInfos) {
                _.each(processor.paramInfos, function(value) {
                    paramInfos.push({
                        description: value.description,
                        name: value.name,
                        value: processorParameters ? processorParameters[value.name] : null
                    });
                });
            };
            return paramInfos;
        };
        $scope.showDetail = function() {
            $scope.showDetail = !$scope.showDetail;
        };

        $scope.changeFile = function(uploadField) {
            Uploader.uploadFile($scope, null, uploadField);
        };
        $scope.ok = function() {
            _.each($scope.moduleConfig.moduleSubModuleConfigs, function(svalue) {
                var tmp = {};
                _.each(svalue.paramInfos, function(value) {
                    tmp[value.name] = value.value;
                });
                svalue.processorParameters = JSON.stringify(tmp);
            });
            pageService.editModule(pageid, idInPage, idInLayout, $scope.moduleConfig)
                .then(function(data) {
                    var returnValue = {
                        "data": data
                    };
                    $modalInstance.close(returnValue);
                }, function(data) {
                    alert("修改失败：" + data);
                });
        };
        $scope.cancel = function() {
            $modalInstance.dismiss('cancel');
        };
    });
